package com.iplus.ydkf.ehome.module.base;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.avos.avoscloud.AVException;
import com.iplus.ydkf.ehome.common.utils.LeanErrorCode;
import com.iplus.ydkf.ehome.config.ConString;

import butterknife.ButterKnife;

/**
 * Created by liuhaitian on 16/4/15.
 */
public abstract class BaseActivity extends AppCompatActivity implements IBaseUi {
    private View rootView;

    protected void logv(String str) {
        if (ConString.LOGGING)
            Log.v(getClass().getSimpleName(), str);
    }

    protected void loge(String str) {
        if (ConString.LOGGING)
            Log.e(getClass().getSimpleName(), str);
    }

    protected void logd(String str) {
        if (ConString.LOGGING)
            Log.d(getClass().getSimpleName(), str);
    }

    protected void logi(String str) {
        if (ConString.LOGGING)
            Log.i(getClass().getSimpleName(), str);
    }

    protected void toast(String str) {
        logd(str);
        Toast.makeText(BaseActivity.this, str, Toast.LENGTH_SHORT).show();
    }

    protected void snackbar(String str) {
        logd(str);
        Snackbar.make(rootView, str, Snackbar.LENGTH_SHORT).show();
    }


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        rootView = getLayoutInflater().inflate(bindLayout(), null);
        setContentView(rootView);
        ButterKnife.bind(this);
        initView(rootView);
        initData(rootView);
    }

    public boolean isNoException(AVException e) {
        if (e == null) return true;
        else {
            try {
                JSONObject errorObject = JSONObject.parseObject(e.getMessage());
                logd(e.getMessage());
                snackbar(LeanErrorCode.getErrorMessage(errorObject.getIntValue("code")));
            } catch (Exception e1) {
                logd(e.getMessage());
                snackbar(LeanErrorCode.getErrorMessage(e.getCode()));
            }
            return false;
        }
    }
}
